
cap program drop tabmat
program tabmat
version 8
syntax varname [if] [in] [fweight aweight] , matrix(string)

preserve
tempvar freq
  gen `freq' = 1
  collapse (count) `freq' `if' `in' [`weight' `exp'], by(`varlist')
  rename `freq' freq
  egen percent = pc(freq)
  mkmat  percent, mat(`matrix')

  forval i = 1/`= rowsof(`matrix')' {
      local name : label (`varlist') `= `varlist'[`i']'
      if `"`name'"' == "" local name = `varlist'[`i']
      if `"`name'"' == "." local name "missing"
      local names `"`names' `"`name'"' "'
  }

  matrix rownames `matrix' = `names'
end


cap program drop tabmat2
program tabmat2
version 8
syntax varname [if] [in] [fweight aweight] , matrix(string)

preserve
tempvar freq
  gen `freq' = 1
  collapse (count) `freq' `if' `in' [`weight' `exp'], by(`varlist')
  rename `freq' freq
  egen percent = pc(freq)
  mkmat  freq , mat(`matrix')

  forval i = 1/`= rowsof(`matrix')' {
      local name : label (`varlist') `= `varlist'[`i']'
      if `"`name'"' == "" local name = `varlist'[`i']
      if `"`name'"' == "." local name "missing"
      local names `"`names' `"`name'"' "'
  }

  matrix rownames `matrix' = `names'
end
